package com.coder.rental.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.User;
import com.coder.rental.entity.UserRole;
import com.coder.rental.mapper.UserMapper;
import com.coder.rental.mapper.UserRoleMapper;
import com.coder.rental.service.IOssService;
import com.coder.rental.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 权限_用户管理 服务实现类
 * </p>
 *
 * @author zhaojj
 * @since 2025-01-10
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private IOssService ossService;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UserMapper userMapper;
    @Override
    public User selectByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(); // mybatisplus中的条件构造器
        queryWrapper.eq("username", username); // 相当于条件where username = ?
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<String> selectRoleByUserId(int userId) {
        return baseMapper.selectRoleByUserId(userId);
    }

    @Override
    public Page<User> searchByPage(Page<User> page, User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(user.getDeptId()!=null && user.getDeptId()==0){
            return baseMapper.selectPage(page,null);
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(user.getDeptId()), "dept_id", user.getDeptId());
        queryWrapper.like(StrUtil.isNotBlank(user.getUsername()), "username", user.getUsername());
        queryWrapper.like(StrUtil.isNotBlank(user.getRealname()), "realname", user.getRealname());
        queryWrapper.like(StrUtil.isNotBlank(user.getNickname()), "nickname", user.getNickname());
        queryWrapper.like(StrUtil.isNotBlank(user.getPhone()), "phone", user.getPhone());
        queryWrapper.like(StrUtil.isNotBlank(user.getEmail()), "email", user.getEmail());
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean delete(String ids) {
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).toList();
        try {
            if(!list.isEmpty()){
                list.forEach(id->{
                    User user= baseMapper.selectById(id);
                    if(user.getIsAdmin()!=null && user.getIsAdmin()!=1){
                        // 删除时，要提示删除用户的头像
                        if(user.getAvatar()!=null){
                            ossService.delete(user.getAvatar());
                        }
                        // 删除用户
                        baseMapper.deleteById(id);
                        // 删除用户和角色关联表数据
                        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", id));
                    }

                });
            }
            return true;
        }catch (Exception e){
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public boolean bindRole(Integer userId, List<Integer> list) {
        // 查询超级管理员角色id
        Integer superAdminRoleId = getSuperAdminRoleId();
        // 先删除当前用户和角色的关联
        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));
        // 添加新的关联并更新 isAdmin字段
        if(!list.isEmpty()){
            list.forEach(roleId->{
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            });
            Integer isAdmin = list.contains(superAdminRoleId)? 1:0;
            updateUserIsAdmin(userId,isAdmin);
            return true;
        }
        return false;
    }
    // 获取超级管理员角色id
    private Integer getSuperAdminRoleId(){
        // 超级管理员角色中的isAdmin属性值为1
        List<User> users =userMapper.selectList(new QueryWrapper<User>().eq("is_admin", 1));
        return users.get(0).getId();
    }
    // 更新User中的isAdmin字段
    private void updateUserIsAdmin(Integer userId,Integer isAdmin){
        User user = new User();
        user.setId(userId);
        user.setIsAdmin(isAdmin);
        baseMapper.updateById(user);
    }

    @Override
    public User selectById(Integer userId) {
        return baseMapper.selectById(userId);
    }
}
